﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Security;
using DataLayer.Entities;
using DataLayer.Implementations;

namespace DonutMgmtSystemFoundation.Helpers
{
    public class SessionContext
    {
        public static void SetAuthenticationToken(string name, bool isPersistant, User userData)
        {
            string data = null;
            if (userData != null)
                data = new JavaScriptSerializer().Serialize(userData);

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, name, DateTime.Now, DateTime.Now.AddYears(1), isPersistant, userData.UserId.ToString());

            string cookieData = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieData)
            {
                HttpOnly = true,
                Expires = ticket.Expiration
            };

            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        public static User GetUserData()
        {
            User userData = null;

            try
            {
                HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
                if (cookie != null)
                {
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
                    new JavaScriptSerializer().Deserialize(ticket.UserData, typeof(int));
                    int? userId = (int?)(new JavaScriptSerializer().Deserialize(ticket.UserData, typeof(int?)));
                    if (userId != null)
                    {
                        UserApplication userApp = new UserApplication();
                        userData = userApp.GetById(userId.Value);
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }

            return userData;
        }

        public static void Logout()
        {
            FormsAuthentication.SignOut();
        }

        public static HttpCookie SetLanguage(string language)
        {
            HttpCookie cookie = new HttpCookie("language", language)
            {
                HttpOnly = true,
                Expires = DateTime.Today.AddYears(1)
            };
            HttpContext.Current.Response.Cookies.Add(cookie);
            return cookie;
        }

        public static string GetLanguage()
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies["language"];
            if (cookie == null || cookie.Value == "undefined" ||  cookie.Value == null || string.IsNullOrEmpty(cookie.Value))
            {
                cookie = SetLanguage("en");
            }
            return cookie.Value;
        }
    }
}